<template>
  <div>
    <!-- 添加模块 -->
    <div style="margin-bottom: 10px;">
      <el-button type="success" @click="handleAdd()">新增角色</el-button>
    </div>
    <!-- 新增角色弹窗 -->
    <el-dialog v-model="showAddForm" title="新增角色" width="40%">
      <el-form label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="name" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAddRole()">添加</el-button>
          <el-button @click="showAddForm = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配菜单弹窗 -->
    <el-dialog v-if="showMenuForm" v-model="showMenuForm" title="分配菜单" width="40%">
      <el-tree ref="treeRef" style="max-width: 600px" :data="MenuListData" show-checkbox default-expand-all
        node-key="permId" :default-checked-keys="defaultCheckedKeys" highlight-current :props="defaultProps"
        @check-change="handleCheckChangeMenu" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="showMenuForm = false">取 消</el-button>
        <el-button type="primary" @click="handleReallocatePermission()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配按钮弹窗 -->
    <el-dialog v-if="showButtonForm" v-model="showButtonForm" title="分配按钮" width="40%">
      <el-tree ref="treeRef" style="max-width: 600px" :data="ButtonListData" show-checkbox default-expand-all
        node-key="permId" :default-checked-keys="defaultCheckedKeys" highlight-current :props="defaultProps"
        @check-change="handleCheckChangeButton" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="showButtonForm = false">取 消</el-button>
        <el-button type="primary" @click="handleReallocatePermission()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限弹窗 -->
    <el-dialog v-if="showPermissionForm" v-model="showPermissionForm" title="分配权限" width="40%">
      <el-tree ref="treeRef" style="max-width: 600px" :data="PermissionListData" show-checkbox default-expand-all
        node-key="permId" :default-checked-keys="defaultCheckedKeys" highlight-current :props="defaultProps"
        @check-change="handleCheckChangePermission" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="showPermissionForm = false">取 消</el-button>
        <el-button type="primary" @click="handleReallocatePermission()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 菜单数据详情表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="roleId" label="序号" width="150" />
      <el-table-column prop="roleName" label="角色名称" width="150" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" @click="handleMenu(scope.row.roleId)">分配菜单</el-button>
          <el-button type="primary" @click="handleButton(scope.row.roleId)">分配按钮</el-button>
          <el-button type="primary" @click="handlePermission(scope.row.roleId)">分配权限</el-button>
          <el-button v-if="hasDeleteButton" type="danger" @click="handleDelete(scope.row.roleId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

  </div>
</template>
  
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElButton, ElTable, ElTableColumn, ElMessage, ElMessageBox, ElTree } from 'element-plus';
import { deleteRoleApi, addRoleApi, reallocatePermApi, roleAllListApi, getDataByRoleApi, roleListApi } from '@/api/api';
import { computed } from 'vue';

interface Tree {
  id: number;
  title: string;
  label: string;
  children?: Tree[];
}

// 格式化时间的方法  去掉T
const formatTime = (time: string) => {
  if (!time) return '';
  return time.replace('T', ' ');
}

// 表格数据
const tableData = ref([]);
// 角色名称
const name = ref('');
//权限类型
const type = ref('');

// 是否显示添加表单
const showAddForm = ref(false);

// 是否显示分配表单
const showMenuForm = ref(false);
const showButtonForm = ref(false);
const showPermissionForm = ref(false);

// 列表数据
const MenuListData = ref([]);
const ButtonListData = ref([]);
const PermissionListData = ref([]);

// 默认选中的节点ID数组
const defaultCheckedKeys = ref([]);

// 角色ID，用于分配菜单
const roleIdForAllocation = ref<number | null>(null);


// 树的配置项    绑定对应数据名称
const defaultProps = {
  id: 'permId',
  children: 'children',
  label: 'permRemark',
};


// 为每个弹窗分别创建一个treeRef引用
const treeRef = ref<any | null>(null);

// 打开新增角色弹窗
const handleAdd = () => {
  showAddForm.value = true;
};

// 角色列表
const roleList = async () => {
  const response = await roleListApi();
  if (response.code === 200) {
    tableData.value = response.data;
  } else {
    ElMessage.error('获取角色列表失败');
  }
}

// 打开分配菜单弹窗，获取菜单数据
const handleMenu = async (id: number) => {
  showMenuForm.value = true;
  type.value = '菜单';
  handleTotalChange(id);
};

// 打开分配按钮弹窗，获取按钮数据
const handleButton = async (id: number) => {
  showButtonForm.value = true;
  type.value = '按钮';
  handleTotalChange(id);
};

// 打开分配按钮弹窗，获取权限数据
const handlePermission = async (id: number) => {
  showPermissionForm.value = true;
  type.value = 'API';
  handleTotalChange(id);
};

// 处理分配表单的默认数据  都是一个接口
const handleTotalChange = async (id: number) => {
  defaultCheckedKeys.value = [];
  roleIdForAllocation.value = id;
  const response = await getDataByRoleApi({ roleId: id, type: type.value });
  console.log('获取角色权限返回结果', response);
  if (response.code === 200) {
    // 根据后端返回的数据计算默认选中的节点ID
    defaultCheckedKeys.value = response.data;
  } else {
    ElMessage.error('获取菜单数据失败');
  }
}


// 处理权限分配
async function handleReallocatePermission() {
  const checkedKeys = treeRef.value?.getCheckedKeys() || [];
  console.log('分配权限选中值', checkedKeys);

  // 调用分配接口
  const response = await reallocatePermApi({ roleId: roleIdForAllocation.value, permIds: checkedKeys, type: type.value });
  console.log('分配权限返回结果', response);
  if (response.code === 200) {
    ElMessage.success('分配成功');
    if (type.value === 'API') {
      showPermissionForm.value = false;
    } else if (type.value === '菜单') {
      showMenuForm.value = false;
    } else if (type.value === '按钮') {
      showButtonForm.value = false;
    }
  } else {
    ElMessage.error('分配失败');
  }
}

async function handleCheckChangeMenu() {

}
async function handleCheckChangeButton() {

}
async function handleCheckChangePermission() {

}


// 提交新增角色
async function handleAddRole() {
  if (!name.value) {
    ElMessage.error('角色名称不能为空');
    return;
  }


  const response = await addRoleApi({ roleName: name.value });
  if (response.code === 200) {
    ElMessage.success('新增成功');
    roleList();
    name.value = '';
    showAddForm.value = false;
  } else {
    ElMessage.error('新增失败');
  }
}

// 删除角色
const handleDelete = async (id: number) => {
  ElMessageBox.confirm(
    '确认删除该角色?',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await deleteRoleApi(id);
      if (response.code === 200) {
        ElMessage.success('删除成功');
        roleList();
      } else {
        ElMessage.error(response.msg);
      }
    } catch (error) {
      ElMessage.error('操作失败');
    }
  }).catch(() => {
    ElMessage.info('已取消');
  });
}

// 全部默认数据
const fun = async () => {
  const response = await roleAllListApi();
  console.log('获取角色全部列表返回结果', response);
  if (response.code === 200) {
    tableData.value = response.data.roleList;
    MenuListData.value = response.data.menuList;
    ButtonListData.value = response.data.buttonList;
    PermissionListData.value = response.data.permissionList;
  } else {
    ElMessage.error('获取角色列表失败');
  }
}

// 按钮权限列表
const buttonList=ref([]);
const hasDeleteButton = computed(() => {
  return buttonList.value.some(button => button === 'delete');
});


// 页面加载完后，加载默认数据
onMounted(() => {
  fun();
  const storedButtons = localStorage.getItem('buttonList');
  if (storedButtons) {
    buttonList.value = JSON.parse(storedButtons);
  }
});
</script>
  
<style scoped></style>
